import React, { Component } from "react";
import PropTypes from "prop-types";

import "./index.css";

export default class Item extends Component {
    static propTypes = {
        id: PropTypes.string.isRequired,
        name: PropTypes.string.isRequired,
        done: PropTypes.bool.isRequired,
        deleteTodo: PropTypes.func.isRequired,
        changeTodo: PropTypes.func.isRequired,
    };

    // 标识鼠标移入移出操作
    state = { mouse: false };

    handleDelete = (id) => {
        return () => {
            const needDelete = window.confirm("确定要删除吗？");
            if (needDelete) {
                this.props.deleteTodo(id);
            }
        };
    };

    handleMouse = (flag) => {
        return () => {
            this.setState({ mouse: flag });
        };
    };

    handleCheck = (id) => {
        return (event) => {
            const isCheck = event.target.checked;

            this.props.changeTodo(id, isCheck);
        };
    };

    render() {
        const { id, name, done } = this.props;
        const { mouse } = this.state;

        // 需要注意checkbox的defaultChecked只在第一次渲染组件时起作用，后续不再起作用，此属性通常不会使用
        // 通常会使用checked和onChange的组合
        return (
            <li
                style={{ backgroundColor: mouse ? "#ddd" : "white" }}
                onMouseEnter={this.handleMouse(true)}
                onMouseLeave={this.handleMouse(false)}
            >
                <label>
                    <input
                        type="checkbox"
                        checked={done}
                        onChange={this.handleCheck(id)}
                    />
                    <span>{name}</span>
                </label>
                <button
                    className="btn btn-danger"
                    style={{ display: mouse ? "" : "none" }}
                    onClick={this.handleDelete(id)}
                >
                    删除
                </button>
            </li>
        );
    }
}
